import { BrowserWindow, IpcMainEvent, IpcMainInvokeEvent } from 'electron'
import { OptionsType, createWindow } from './createWindow'

export const config = {
  search: {
    id: 0,
    options: {
      hash: '',
      openDevTools: false
    }
  },
  code: {
    id: 0,
    options: {
      width: 1060,
      height: 600,
      frame: true,
      transparent: false,
      openDevTools: false,
      hash: '/#config/category/contentList'
    }
  },
  config: {
    id: 0,
    options: {
      width: 500,
      height: 350,
      frame: true,
      transparent: false,
      openDevTools: false,
      hash: '/#config'
    }
  }
} as Record<WindowNameType, { id: number; options: OptionsType }>

// 根据窗口名称获取窗口实例
export const getWindowByName = (name: WindowNameType) => {
  // 通过id获取窗口实例，默认id为0，肯定不存在该窗口；而在第一次创建后改变id
  let win = BrowserWindow.fromId(config[name].id)
  // 不存在窗口则创建
  if (!win) {
    win = createWindow(config[name].options)
    config[name].id = win.id
  }
  return win
}

// 根据触发事件的来源获取窗口实例
export const getWindowByEvent = (event: IpcMainEvent | IpcMainInvokeEvent) => {
  return BrowserWindow.fromWebContents(event.sender)!
}

// 默认打开窗口（调试用），在./index.tsx文件中registerAppGlobleShortcut()方法已默认打开search窗口
// app.whenReady().then(() => {
//   // getWindowByName('search')
//   // getWindowByName('config')
// })
